package com.cn.zengzeng.spbzengzeng.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.cn.zengzeng.spbzengzeng.enums.CodeAndMsgEnum;
import com.cn.zengzeng.spbzengzeng.exception.MyUnDefindException;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * 提供jwt令牌生成和校验的工具类
 * @Author: zengzeng
 * @Date: 2021/5/30 0030 21:17
 */
@Slf4j
public class JwtUtils {
    private JwtUtils(){
    }

    /**
     * 用户登录成功后生成jwt
     * 使用HMAC256算法     私钥使用用户密码
     * 创建令牌
     */
    private static final long EXPIRE_TIME = 60*60*24*1000L;
    private static final String SECRECT = "jwt_secect";

    public static String sign (String username) {

        //构造失效时钟
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        JWTCreator.Builder builder = JWT.create();
        //给jwt令牌payload放入发令牌的用户
        builder.withAudience(username);

        //设置令牌的失效时间
        builder.withExpiresAt(date);

        //对令牌载荷进行加密
        Algorithm algorithm = Algorithm.HMAC256(SECRECT);
        return builder.sign(algorithm);

    }

    public static void main (String[] args) {
        String zhangasan = sign("zhangasan");
        System.out.println("zhangasan = " + zhangasan);
    }
    /**
    * 验证令牌
    * @author ZhangZengZeng
    * @date 2022/9/22 16:47
    * @param token  token
    * @return {@link boolean}
    */
    public static boolean verifyToken (String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRECT);
            //生成校验器
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            jwtVerifier.verify(token);
            //无异常则校验成功
            return true;
        }catch(Exception e) {
            throw new MyUnDefindException(CodeAndMsgEnum.TOKEN.getCode(),CodeAndMsgEnum.TOKEN.getDescription());
        }
    }
}
